<template>
  <main-card-admin :title="`在线服务详情（${detailInfo?.onlineId || ''}）`" :crumbs="crumbs" :screen-style-obj="{ padding: '0 0 24px' }">
    <template #screen-space>
      <a-row class="time-module">
        <a-col class="mr-16 label">应用创建时间</a-col>
        <a-col class="mr-24 val">{{ detailInfo?.createTime }}</a-col>
        <a-col class="mr-24">
          <svg xmlns="http://www.w3.org/2000/svg" width="2" height="20" viewBox="0 0 2 20" fill="none">
            <path d="M1 0V20" stroke="#D9D9DB" />
          </svg>
        </a-col>
        <a-col class="mr-16 label">应用更新时间</a-col>
        <a-col class="mr-24 val">{{ detailInfo?.updateTime }}</a-col>
      </a-row>
    </template>
    <div class="page-body">
      <info-module :height="672" :info-arr="clientInfoArr" />
      <div class="table">
        <a-table
          style="height: 672px"
          :columns="tableColumns"
          :data-source="detailInfo?.apiList"
          :loading="loading"
          :pagination="false"
          :scroll="tableScroll"
          class="header-right-angle admin-table"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex == 'totalCallNum'"> {{ record.usedCallNum }}/{{ record.totalCallNum }} </template>
            <template v-else-if="column.dataIndex === 'time'"> {{ record.beforeValidTime }} - {{ record.afterValidTime }} </template>
            <template v-else-if="column.dataIndex == 'operateMethodStatus'">
              <a-tooltip v-if="statusObj[record.operateMethodStatus].tooltip" placement="bottom">
                <template #title>
                  <span>{{ record.operateMethodStatus?.substring(1) }}时间 {{ record?.operateMethodTime || '' }}</span>
                </template>
                {{ record.operateMethodStatus || '' }}
              </a-tooltip>
              <span v-else>{{ record.operateMethodStatus || '' }}</span>
            </template>
            <template v-else-if="column.dataIndex === 'operation'">
              <div @click.stop="">
                <a-button v-auth="'online-service-edit-auth'" type="link" class="mr-16" @click="handleOpenApiForm(record.id)">
                  编辑
                </a-button>
                <a-button v-auth="'auth-manage'" type="link" class="mr-16" @click="handleOpenAuthRecord(record.id, record)">
                  授权记录
                </a-button>
              </div>
            </template>
          </template>
        </a-table>
      </div>
    </div>
  </main-card-admin>
  <auth-form ref="authFormRef" @on-success="getClientInfo(clientId)" />
  <auth-record ref="authRecordRef" />
</template>

<script setup lang="ts">
  import { computed, ref } from 'vue'
  import { useRoute } from 'vue-router'

  import MainCardAdmin, { Crumb } from '@/components/MainCardAdmin/index.vue'
  import { authApi } from '@/services/api'
  import { filterTableColumns } from '@/utils/ant-component'

  import { statusObj } from '../common'
  import InfoModule from '../components/InfoCard/index.vue'
  import { DetailInfo } from '../types/online-service'
  import AuthForm from './components/auth-form.vue'
  import AuthRecord from './components/auth-record.vue'
  const route = useRoute()

  const clientId = (route.query.id as string) || ''

  const detailInfo = ref<DetailInfo>()

  const crumbs = computed<Crumb[]>(() => [
    {
      name: '在线服务',
      path: '/auth-manage/online-service/list'
    },
    {
      name: `在线服务详情（${detailInfo.value?.onlineId || ''}）`
    }
  ])

  const clientInfoArr = computed(() => [
    { label: '在线服务ID', val: detailInfo.value?.onlineId || '' },
    { label: 'API Key', val: detailInfo.value?.apiKey || '' },
    { label: 'Secret Key', val: detailInfo.value?.secretKey || '' },
    { label: '用户名称', val: detailInfo.value?.username || '' },
    { label: '应用编号', val: detailInfo.value?.number || '' },
    { label: '应用名称', val: detailInfo.value?.name || '' }
  ])

  const loading = ref(false)
  const getClientInfo = async (id: string) => {
    try {
      loading.value = true
      const { data } = await authApi.detail(id)()

      detailInfo.value = data
      loading.value = false
    } catch (error) {
      loading.value = false
    }
  }

  // 表格
  const tableColumns = ref(
    filterTableColumns([
      {
        title: '算法服务',
        dataIndex: 'algoName',
        width: 100
      },
      {
        title: '版本号',
        dataIndex: 'version',
        width: 100
      },
      {
        title: '调用量',
        dataIndex: 'totalCallNum',
        width: 100
      },
      {
        title: 'QPS',
        dataIndex: 'qps',
        width: 100
      },
      {
        title: '应用服务状态',
        dataIndex: 'appStatus',
        width: 130
      },
      {
        title: '算法运行状态',
        dataIndex: 'operateMethodStatus',
        width: 130
      },
      {
        title: '有效期',
        dataIndex: 'time',
        width: 310
      },
      {
        title: '授权时间',
        dataIndex: 'authTime',
        width: 233
      },
      {
        title: '',
        dataIndex: 'operation',
        width: 140,
        fixed: 'right'
      }
    ])
  )

  const tableScroll = computed(() => {
    const scrollX = tableColumns.value.reduce((prev, curr) => {
      return prev + (curr.width as number)
    }, 0)
    return scrollX > 1022 ? { x: scrollX } : undefined
  })

  // const isShowEditBtn = (row: Record<string, any>) => {
  //   const codeList: number[] = [0, 1, 2, 3, 4, 5]
  //   return codeList.includes(row.appStatusCode as number)
  // }

  getClientInfo(clientId)

  // 编辑API
  const authFormRef = ref<InstanceType<typeof AuthForm>>()
  const handleOpenApiForm = (id: string) => {
    authFormRef.value?.openModal(id)
  }

  // 授权记录
  const authRecordRef = ref<InstanceType<typeof AuthRecord>>()
  const handleOpenAuthRecord = (id: string, record: Record<string, any>) => {
    authRecordRef.value?.openModal(id, { ...record, ...detailInfo.value })
  }
</script>

<style lang="less" scoped>
  @import '@/styles/mixins.less';

  .time-module {
    display: flex;
    align-items: center;
    padding: 8px 24px;
    font-size: 12px;
    background: @background3;
    border-radius: 6px;

    .label {
      color: @text03;
    }

    .val {
      color: @text01;
    }
  }

  .page-body {
    display: flex;
    gap: 0 40px;
    height: 100%;

    .table {
      display: flex;
      overflow-x: auto;
      height: 100%;
      flex: 1;
    }
  }
</style>
